// import type { Plugin } from 'vite';
import { PluginOptions } from './types';
import { genInitConfig } from './build/initConfig';
import { EXT_NAME } from './constant/index';
import { hotReload } from './tools/hotReloadFn';
import { getConfig, setConfig, readConfigFile } from './config/index';
import { getExtName } from './tools/utils';

const fs = require('fs');
const fs2 = fs.promises;
const micromatch = require('micromatch');

export default function Autocss(options?: PluginOptions) {
	let globalConfig : any = null;
	
	return {
		// 插件名称
		name: 'kux-autocss',

		// pre 会比 post 先执行
		enforce: 'pre',

		// 指明仅在 'build/serve' 环境调用
		// apply: 'serve',

		async config(config, { command }) {
			// console.log('这里是config钩子');
			await genInitConfig(config, options);
			// await loadUserConfig()
			// setConfig(readConfigFile());
			// setConfig(autocssConfig);
			globalConfig = Object.assign(config, setConfig(readConfigFile(options)))
			return config;
		},

		async configResolved(resolvedConfig) {
			// console.log('这里是configResolved钩子');
			// await loadUserConfig()
		},

		configureServer(server) {
			// console.log('这里是configureServer钩子');
		},

		transformIndexHtml(html) {
			// console.log('这里是transformIndexHtml钩子');
		},

		async transform(code, id) {
			const matchLetter : RegExpMatchArray | null = code.match(/(?<=\.)([\w\d]+)$/);
			if (matchLetter && !getConfig(EXT_NAME).includes(matchLetter[0])) {
				console.log('not match');
				return undefined;
			}

			/**
			 * 过滤文件
			 */
			const path = require('path');
			// 追加根目录到 includePatterns
			const root = process.env.UNI_INPUT_DIR || process.env.UNI_CLI_CONTEXT
			let includePaths = globalConfig?.include?.map(pattern => path.posix.join(root, pattern)) || [`${root}/pages/**`];
			if (!includePaths.length) {
				includePaths = [`${root}/pages/**`];
			}
			const excludePaths = globalConfig?.exclude?.map(pattern => path.posix.join(root, pattern));
			
			if (micromatch.isMatch(id, excludePaths)) {
				return null
			}
			
			let newCode = code;
			if (micromatch.isMatch(id, includePaths)) {
				const extName = getExtName(id)
				if (globalConfig?.extName.includes(`${extName}`)) {
					console.log('监听到目标文件修改：', id);
					const { css, sourceCode } = await hotReload(code, extName);
					newCode = sourceCode
				}
			}
			
			return {
				code: newCode,
				map: null
			}
		}

		// handleHotUpdate({ file, read }) {
		// 	console.log('这里是修改代码热更新监听内容');
		// }
	}
}

// export function defineConfig(config: AutocssConfig): AutocssConfig {
// 	return config;
// }